from src.util.Route import *
from src.service import HandleManageService


# 获取系统 所有的接口(分页 所有信息)
@route("/handle/get/all", methods=['POST'])
def handleGetAll():
    data = request.json
    num = data.get("num")
    size = data.get("size")
    cdn = data.get('cdn') or {}
    page = Page(num=num, size=size)  # Create a Page object
    r = HandleManageService.getHandleAll(page, cdn)
    return R.success(r)


# 获取系统所有的接口 (分页 id 接口名字)
@route("/handle/get/name", methods=['POST'])
def handleGetName():
    data = request.json
    num = data.get("num")
    size = data.get("size")
    cdn = data.get('cdn')
    if cdn is None:
        cdn = dict()
    page = Page(num=num, size=size)  # Create a Page object
    r = HandleManageService.getHandleName(page, cdn)
    return R.success(r)


# 添加系统接口
@route("/handle/add", methods=['POST'])
def handleAdd():
    data: dict = request.json
    data = formatParam(data, ['hId'])
    r = HandleManageService.addHandle(data)
    if r:
        return R.success(r, "系统接口添加成功")
    else:
        return R.create(400, r, '系统接口添加失败')


# 修改系统接口 （字段校验）
@route("/handle/update", methods=['POST'])
def handleUpdate():
    k: dict = request.json
    r = HandleManageService.updateHandle(k)
    if r:
        return R.success(r, "系统接口修改成功")
    else:
        return R.create(400, r, '系统接口修改失败')


# 删除系统接口 （使用事务删除映射关系）
@route("/handle/del", methods=['POST'])
def handleDelete():
    hids = request.json
    r = HandleManageService.delHandle(hids)
    if r:
        return R.success(None, "系统接口删除成功")
    else:
        return R.create(400, None, '系统接口删除失败')


@route('/handle/log', methods=['POST'])
def handleLogChange():
    hids = request.json['hids']
    status = request.json['log']
    r = HandleManageService.handleLog(hids, status)
    if r:
        return R.success(None, '操作成功')
    return R.bad_request('操作失败')
